package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spbsu.electromenu.model.Session;
import ru.spbsu.electromenu.model.Table;
import ru.spbsu.electromenu.serialization.DeserializationException;
import ru.spbsu.electromenu.serialization.SerializationException;
import ru.spbsu.electromenu.service.SessionService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Date: 3/23/11
 * Time: 9:15 PM
 *
 * @author Artem Titov
 */
public class ChangeTableServlet extends ClientHttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(ChangeTableServlet.class);

    private SessionService sessionService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sessionService = getBean("sessionService");
        if (sessionService == null) {
            logger.error("Failed to instantiate necessary services");
            isValid = false;
            throw new IllegalStateException("Failed to instantiate necessary services");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!isValid) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        PrintWriter out = null;
        try {
            final Table table = deserializer.deserializeTable(request.getParameter("request"));

            final Session session = new Session();
            session.setTableId(table.getId());
            sessionService.put(session);

            final String responseSource = serializer.serializeSession(session);
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.print(responseSource);
        } catch (DeserializationException e) {
            logger.error("Failed to deserialize table", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SerializationException e) {
            logger.error("Failed to serialize session", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            logger.error("Internal fail", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Throwable t) {
            logger.error("Unexpected fail", t);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
